import {messages} from "share/common";
/**
 * 操作：提交按钮
 * 适用：行程卡片的差旅申请单
 */
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Form, Button, message, Modal, Row, Col, Switch, Select } from 'antd'
const Option = Select.Option;
import travelService from 'containers/request/travel-request/travel.service'
import requestService from 'containers/request/request.service'
import errorMessage from 'share/errorMessage';
import requestUtil from 'containers/request/slide/request-util'
import travelUtil from 'containers/request/travel-request/travelUtil'
import Condition from 'components/condition';
const If = Condition.If;
import moment from 'moment';
import Designate from 'components/template/designate'
import 'styles/expense-report/components/expense-check-result.scss'  //提交校验的弹框样式

class SubmitBtn extends React.Component{
  travelErrorList = []; //差旅单提交校验错误信息暂存列表
  travelParams = {}; //差旅单提交参数
  constructor(props) {
    super(props);
    this.state = {
      submitLoading: false,
      itineraryHeadList: [], //行程相关信息
      isShowModal: false, //统一订票弹框
      selectPerson: [], //统一订票可选人范围
      platformPerson: [], //统一订票订票平台的可选人范围
      maxHotel: {},//最大房间数接口返回数据
      uniformShow: {
        flight: false,
        flightPlatform: false,
        train: false,
        hotel: false,
        dining: false
      }, //统一订票是否显示
      uniformSwitchShow: {
        flight: false,
        train: false,
        hotel: false,
        dining: false
      }, //统一订票上的开关是否显示
      uniformValue: {
        isFlight: false,
        isTrain: false,
        isHotel: false,
        isDining: false
      }, //统一订票开关的值
      //统一订票的统一订票人
      flightPerson: '',
      flightPlatformPerson: '',
      trainPerson: '',
      hotelPerson: '',
      diningPerson: '',
      randomHotel: false, //随机酒店合住人的loading
      maleUserOIDs: [],
      femaleUserOIDs: [],
      submitCheckVisible: false, //差旅提交前的校验结果弹窗
      designateVisible: false, //指派的弹框是否展示
      nodeList: [], //未来节点list
      disableSubmit: false, // 没有统一订票人则不允许提交单据
    }
  }

  processQuotaValues = (params) => {
    const { quotaObj } = this.props;
    params.takeQuota = quotaObj.takeQuota;
    params.quotaCurrencyCode = quotaObj.takeQuota ? quotaObj.quotaCurrencyCode : '';
    params.quotaAmount = quotaObj.quotaAmount;
    params.quotaBankCardOID = quotaObj.takeQuota ? quotaObj.quotaBankCardOID : '';
  };

  handleSubmit = () => {
    const { info, form: formInfo, refreshInfo } = this.context;
    let params = JSON.parse(JSON.stringify(info));
    //处理额度相关数据
    this.processQuotaValues(params);

    //处理加签人数据
    params.countersignApproverOIDs = [];
    params.countersignApproverNames && params.countersignApproverNames.forEach(item => {
      params.countersignApproverOIDs.push(item.userOID);
    });

    this.travelErrorList = [];
    this.travelParams = {};
    //todo 校验重复差补

    this.setState({submitLoading: true});
    //校验参与人数据权限
    let isSetSelectParticipant = false;//是否配置了参与人字段，如果配置了且是开启内部参与人，则需要校验
    params.custFormValues.map(item =>{
      if(item.messageKey === 'select_participant'){
        isSetSelectParticipant = true;
        if (item.fieldContent) {
          isSetSelectParticipant = JSON.parse(item.fieldContent).isUse;
        }
        //内部参与人不必填的时候，没选内部参与人员就不需要进行权限校验了
        let parts = JSON.parse(item.value ? item.value : '[]');
        if (!parts.length) {
          isSetSelectParticipant = false;
        }
      }
    });
    if(isSetSelectParticipant){
      travelService.travelValidate(params, this.props.language, formInfo).then(res => {//参与人权限校验
        let showName = "";
        res.data.map(item => {
          if (item.errorDetail) {
            showName = `${showName} ${item.fullName}`;
          }
        });
        if (showName) {
          //弹框提示是否删除不在权限内的参与人
          Modal.confirm({
            title: messages('common.info')/*提示*/,
            content: <div>
              <p>{messages('request-1.key110',{arg1: showName})/*{arg1} 不在可选人员范围内*/}</p>
            </div>,
            okText: messages('common.cancel')/*取消*/,
            onOk: () => {this.setState({submitLoading: false});}
          });
        } else {
          //继续提交
          this.travelParams = params;
          this.checkedItinerary();
        }
      }).catch(err => {
        this.setState({submitLoading: false});
        let error = err.response.data;
        if (error.validationErrors && error.validationErrors.length) {
          if(error.validationErrors[0].externalPropertyName){
            switch (error.validationErrors[0].externalPropertyName) {
              case '2010': //申请人为空
                message.error(messages('request-1.key111')/*申请人为空.*/);
                break;
              case '2011': //部门为空
                message.error(messages('request-1.key112')/*部门为空.*/);
                break;
              case '2012': //成本中心为空
                message.error(messages('request-1.key113')/*成本中心为空.*/);
                break;
              default: message.error(messages('request-1.key114')/*出错了，请联系管理员*/);
            }
          }
        } else {
          message.error(`${messages('common.save.filed')/*保存失败*/}，${error.message}`);
        }
      })
    } else {
      //继续提交
      this.travelParams = params;
      this.checkedItinerary();
    }
  };

  //处理行程相关校验
  checkedItinerary = () => {
    const { info } = this.context;
    const { newProfile } = this.props;
    //let itineraryRequire = newProfile["applicationControlOpt"]["taItineraryRequired"] === "TRUE";
    requestService.getItineraryHead(info.applicationOID, true).then(res => {
      //行程必填校验移到后台了
      // if(itineraryRequire && !(res.data && res.data.length)){
      //   message.warn(messages('request-1.key115')/*请添加行程*/);
      //   this.setState({submitLoading: false});
      //   return;
      // }
      this.setState({itineraryHeadList: res.data}, this.checkedItineraryNext);
    }).catch(err => {
      this.setState({submitLoading: false});
      errorMessage(err.response);
    });
  };

  //处理统一订票逻辑
  checkedItineraryNext = () => {
    const { form: formInfo, info } = this.context;
    const { itineraryHeadList } = this.state;
    let uniformShow = requestUtil.isShowModal(itineraryHeadList, formInfo.customFormPropertyMap);
    let isShowModal = uniformShow.flight || uniformShow.flightPlatform || uniformShow.train || uniformShow.hotel || uniformShow.dining;

    let selectPerson = [];
    selectPerson.push({name: this.travelParams.createdName, oid: this.travelParams.createdBy});//添加创建人
    selectPerson.unshift({name: this.travelParams.applicantName, oid: this.travelParams.applicantOID});//添加申请人
    let participantList = [];
    travelUtil.getFormHeadValue(this.travelParams.custFormValues, 'select_participant').forEach(v => {
      participantList.push({name: v.fullName, oid: v.participantOID});
    });
    selectPerson.push(...participantList);
    selectPerson = requestUtil.processUniformBooking(selectPerson);//去重
    this.setState({uniformShow, isShowModal, selectPerson});

    if (uniformShow.flightPlatform) {
      let platformPerson = [];
      travelService.getUniformBooker().then(res => {
        if (res.data && res.data.length) {
          res.data.forEach(booker => {
            platformPerson.push({name: booker.userName, oid: booker.userOID});
          });
          this.setState({
            platformPerson,
            flightPlatformPerson: info.travelApplication.platformBookingClerkOID ? info.travelApplication.platformBookingClerkOID : platformPerson[0] && platformPerson[0].oid
          });
        } else {
          this.setState({disableSubmit: true});
          message.warning(messages('request-1.key840')/*订票平台无有效预订人，请联系管理员设置订票专员*/)
        }
      }).catch(err => {
        errorMessage(err.response);
      });
    }

    if (uniformShow.hotel) {
      this.setState({
        maleUserOIDs: (info.travelApplication.travelHotelBookingMaleClerks && info.sourceApplicationOID) ? info.travelApplication.travelHotelBookingMaleClerks : [],
        femaleUserOIDs: (info.travelApplication.travelHotelBookingFemaleClerks && info.sourceApplicationOID) ? info.travelApplication.travelHotelBookingFemaleClerks : []
      });
      //获取最大房间数
      let outNum = travelUtil.getFormHeadValue(this.travelParams.custFormValues, 'out_participant_num');
      travelService.getMaxRoom(outNum, travelUtil.getFormHeadValue(this.travelParams.custFormValues, 'select_participant')).then(h => {
        this.setState({maxHotel: h.data});
      }).catch(err => {
        errorMessage(err.response);
      });
    }

    let maps = formInfo.customFormPropertyMap;
    //处理统一订票开关是否显示
    let uniformSwitchShow = {
      flight: travelUtil.processUniformConfig('ca.travel.bookingpreference', maps, 'switch'),
      train: travelUtil.processUniformConfig('ca.travel.train.bookingpreference', maps, 'switch'),
      hotel: travelUtil.processUniformConfig('ca.travel.hotel.bookingpreference', maps, 'switch'),
      dining: travelUtil.processUniformConfig('ca.travel.dining.bookingpreference', maps, 'switch')
    };
    this.setState({uniformSwitchShow});
    //处理开关和人的默认值
    let uniformValue = {
      isFlight: travelUtil.processUniformConfig('ca.travel.bookingpreference', maps, 'default'),
      isTrain: travelUtil.processUniformConfig('ca.travel.train.bookingpreference', maps, 'default'),
      isHotel: travelUtil.processUniformConfig('ca.travel.hotel.bookingpreference', maps, 'default'),
      isDining: travelUtil.processUniformConfig('ca.travel.dining.bookingpreference', maps, 'default')
    };
    if (info.sourceApplicationOID) {
      //更改的单据的默认值
      uniformValue = {
        isFlight: info.travelApplication.uniformBooking,
        isTrain: info.travelApplication.trainUniformBooking,
        isHotel: info.travelApplication.hotelUniformBooking,
        isDining: info.travelApplication.diningUniformBooking
      };
    }
    this.setState({uniformValue});
    //处理统一订票人的默认值
    this.setState({
      flightPerson: info.travelApplication.bookingClerkOID || selectPerson[0].oid,
      trainPerson: info.travelApplication.trainBookingClerkOID || selectPerson[0].oid,
      hotelPerson: info.travelApplication.hotelBookingClerkOID || selectPerson[0].oid,
      diningPerson: info.travelApplication.diningBookingClerkOID || selectPerson[0].oid,
    });

    //没有统一订票
    if (!isShowModal) {
      //没有统一订票的情况处理
      this.goSubmitTravel();
    }
  };

  onChangeSwitch = (type) => {
    let uniformValue = this.state.uniformValue;
    switch (type) {
      case 'flight':
        uniformValue.isFlight = !uniformValue.isFlight;
        break;
      case 'train':
        uniformValue.isTrain = !uniformValue.isTrain;
        break;
      case 'hotel':
        uniformValue.isHotel = !uniformValue.isHotel;
        break;
      case 'dining':
        uniformValue.isDining = !uniformValue.isDining;
        break;
    }
    this.setState({uniformValue});
  };

  handleChangeUniform = (value, type) => {
    switch (type) {
      case 'flight':
        this.setState({flightPerson: value});
        break;
      case 'flightPlatform':
        this.setState({flightPlatformPerson: value});
        break;
      case 'train':
        this.setState({trainPerson: value});
        break;
      case 'hotel':
        this.setState({hotelPerson: value});
        break;
      case 'dining':
        this.setState({diningPerson: value});
        break;
    }
  };

  createHotelPeople = () => {
    this.setState({randomHotel:true});
    travelService.randomCreateHotelPeople(this.state.maxHotel).then(res => {
      this.setState({randomHotel:false, maleUserOIDs: res.data.maleUserOIDs, femaleUserOIDs: res.data.femaleUserOIDs});
    }).catch(err => {
      errorMessage(err.response);
      this.setState({randomHotel:false});
    })
  };

  //选择合住订房间的人
  handleSelectItemValue = (values, key) => {
    this.setState({[key]: values});
  };

  cancelSubmit = () => {
    this.setState({isShowModal: false, submitLoading: false});
  };

  //处理统一订票字段
  goSubmitTravel = () => {
    if (this.state.disableSubmit) {
      message.warning(messages('request-1.key840')/*订票平台无有效预订人，请联系管理员设置订票专员*/);
      return;
    }
    const { uniformShow, uniformValue, flightPerson, flightPlatformPerson, trainPerson, diningPerson, hotelPerson,
      maxHotel, maleUserOIDs, femaleUserOIDs } = this.state;
    if (!this.travelParams.travelApplication) {
      this.travelParams.travelApplication = {};
    }
    if (uniformValue.isFlight) {
      this.travelParams.travelApplication.uniformBooking = true;
      this.travelParams.travelApplication.bookingClerkOID = flightPerson;
    } else {
      this.travelParams.travelApplication.uniformBooking = false;
    }
    //订票平台相关的处理
    if (uniformShow.flightPlatform) {
      this.travelParams.travelApplication.platformBookingClerkOID = flightPlatformPerson;
    }
    if (uniformValue.isTrain) {
      this.travelParams.travelApplication.trainUniformBooking = true;
      this.travelParams.travelApplication.trainBookingClerkOID = trainPerson;
    } else {
      this.travelParams.travelApplication.trainUniformBooking = false;
    }
    if (uniformValue.isDining) {
      this.travelParams.travelApplication.diningUniformBooking = true;
      this.travelParams.travelApplication.diningBookingClerkOID = diningPerson;
    } else {
      this.travelParams.travelApplication.diningUniformBooking = false;
    }
    if (uniformValue.isHotel) {
      this.travelParams.travelApplication.hotelUniformBooking = true;
      this.travelParams.travelApplication.hotelBookingClerkOID = hotelPerson;
    } else {
      this.travelParams.travelApplication.hotelUniformBooking = false;
    }
    //非统一订酒店且有酒店行程 需设置合租人信息
    if (uniformShow.hotel && !uniformValue.isHotel) {
      let man = maleUserOIDs;
      let women = femaleUserOIDs;
      if(man && man.length === maxHotel.maleRoomNumber){
        this.travelParams.travelApplication.travelHotelBookingMaleClerks = man;
      } else if(maxHotel.maleRoomNumber && maxHotel.maleRoomNumber > 0){
        message.error(messages('request-1.key116',{arg1: maxHotel.maleRoomNumber})/*男性合住人需选{arg1}人*/);
        return;
      }
      if(women && women.length === maxHotel.femaleRoomNumber){
        this.travelParams.travelApplication.travelHotelBookingFemaleClerks = women;
      } else if(maxHotel.femaleRoomNumber && maxHotel.femaleRoomNumber > 0){
        message.error(messages('request-1.key117',{arg1: maxHotel.femaleRoomNumber})/*女性合住人需选{arg1}人*/);
        return;
      }
    }
    //如果没有展示选统一订票的，都置为非统一订票
    if (!uniformShow.flight) {
      this.travelParams.travelApplication.uniformBooking = false;
    }
    if (!uniformShow.train) {
      this.travelParams.travelApplication.trainUniformBooking = false;
    }
    if (!uniformShow.dining) {
      this.travelParams.travelApplication.diningUniformBooking = false;
    }
    if (!uniformShow.hotel) {
      this.travelParams.travelApplication.hotelUniformBooking = false;
    }
    this.setState({isShowModal: false}, this.executeTravelSubmit);
  };

  //执行差旅申请单提交接口
  executeTravelSubmit = ()=> {
    if (requestUtil.judgeSubmitSign(this.travelParams)) {
      let errorItem = {
        type: 'WARNING',
        title: messages('request-1.key118')/*已审批通过*/,
        message: messages('request-1.key119',{arg1: requestUtil.judgeSubmitSign(this.travelParams)})/*{arg1}已审批通过*/
      };
      this.travelErrorList.push(errorItem);
    }
    this.combineValidate();
  };

  //提交前调用接口，统一处理强弱管控校验
  combineValidate = () => {
    let params = travelUtil.processDuplicateDateParams(this.travelParams);
    params.applicationOID = this.travelParams.applicationOID;
    travelService.submitCheck(params, this.travelParams).then(res => {
      //处理老的预算校验
      if (!res.data.budgetCheckResult) {
        this.travelErrorList.push({
          type: 'ERROR',
          title: messages('request-1.key120')/*预算校验失败*/,
          message: res.data.budgetCheckErrorMessage
        });
      }

      //处理日期重叠
      let dateCheck = res.data.travelDateCheckResponse || {};
      if (dateCheck.code === '70124' && dateCheck.rows && dateCheck.rows.length) {
        let isShowTime = dateCheck.toDateOverLap === '1003';
        let currentStartDate = isShowTime ? moment(params.startDate).format('YYYY-MM-DD HH:mm') : moment(params.startDate).format('YYYY-MM-DD');
        let currentEndDate = isShowTime ? moment(params.endDate).format('YYYY-MM-DD HH:mm') : moment(params.endDate).format('YYYY-MM-DD');
        let content = (
          <div>
            <div>{messages('request-1.key121',{arg1: currentStartDate,arg2: currentEndDate})/*本单据的出差往返日期（{arg1}~{arg2}）与已提交的单据往返日期重叠，请修改后再提交：*/}</div>
            {dateCheck.rows.map(row => {
              let rowStartDate = isShowTime ? moment(row.startDate).format('YYYY-MM-DD HH:mm') : moment(row.startDate).format('YYYY-MM-DD');
              let rowEndDate = isShowTime ? moment(row.endDate).format('YYYY-MM-DD HH:mm') : moment(row.endDate).format('YYYY-MM-DD');
              return (
                <div>
                  <div>
                    {row.formName}{row.businessCode}，{messages('request-1.key122')/*申请人：*/}{row.applicantName}
                  </div>
                  <div>
                    {rowStartDate}~{rowEndDate}
                  </div>
                </div>
              )
            })}
          </div>
        );
        this.travelErrorList.push({
          type: 'ERROR',
          title: messages('request-1.key123')/*日期重叠*/,
          content: content
        });
      }

      //校验国际行程和人员激活
      let userCheck = res.data.userInfoCheckResponse || {};
      if (userCheck && !userCheck.success) {
        let nameList = [];
        let nameEnableList = [];
        let nameStr = '';
        let nameEnableStr = '';
        userCheck.data && userCheck.data.forEach(user => {
          if (!user.withPassport) {
            nameList.push(user.userName);
          }
        });
        nameStr = nameList.join(' | ');
        if (nameStr) {
          this.travelErrorList.push({
            key: 'user',
            type: 'WARNING',
            title: messages('request-1.key124')/*护照信息未维护*/,
            message: messages('request-1.key125',{arg1: nameStr})/*单据包含国际行程，有尚未维护护照的人员，可能影响预订：{arg1}*/
          });
        }
        userCheck.vendorCheckResult && userCheck.vendorCheckResult.forEach(user => {
          if (!user.vendorEnable) {
            nameEnableList.push(user.userName);
          }
        });
        nameEnableStr = nameEnableList.join(' | ');
        if (nameEnableStr) {
          this.travelErrorList.push({
            key: 'user',
            type: 'WARNING',
            title: messages('request-1.key126')/*参与人未激活*/,
            message: messages('request-1.key127',{arg1: nameEnableStr})/*单据参与人中，有在携程尚未激活的人员，可能影响预订（可联系管理员维护）: {arg1}*/
          });
        }
      }

      //处理行程不连续校验
      let unContinuousItineraryHeadList = res.data.unContinuousItineraryHeadList || [];
      if (unContinuousItineraryHeadList.length) {
        let content = (
          <div>
            <div>{messages('request-1.key128')/*以下行程不连续，请返回修改后再提交：*/}</div>
            {unContinuousItineraryHeadList.map(row => {
              let rowStartDate = moment(row.startDate).format('YYYY-MM-DD');
              let rowEndDate = moment(row.endDate).format('YYYY-MM-DD');
              return (
                <div>
                  {rowStartDate}~{rowEndDate}&nbsp;&nbsp;&nbsp;{row.fromCityName}-{row.toCityName}
                </div>
              )
            })}
          </div>
        );
        this.travelErrorList.push({
          type: 'ERROR',
          title: messages('request-1.key129')/*行程不连续*/,
          content: content
        });
      }

      //校验行程地点不匹配
      let travelVendorCityCheckResponses = res.data.travelVendorCityCheckResponses || [];
      if (travelVendorCityCheckResponses.length) {
        let content = (
          <div>
            {travelVendorCityCheckResponses.map(row => {
              let expenseNameStr = (row.unSupportBudgetDTOs || []).map(item => item.expenseTypeName).join('、');
              return (
                <div>
                  {row.itineraryHeadDTO.fromCityName}-{row.itineraryHeadDTO.toCityName}：{expenseNameStr}
                </div>
              )
            })}
          </div>
        );
        this.travelErrorList.push({
          type: 'ERROR',
          title: messages('request-1.key130')/*以下明细不支持行程所选城市*/,
          content: content
        });
      }

      //处理必填项的校验
      let travelItineraryBudgetCheckResponses = res.data.travelItineraryBudgetCheckResponses || [];
      if (travelItineraryBudgetCheckResponses.length) {
        let content = (
          <div>
            {travelItineraryBudgetCheckResponses.map(row => {
              let expenseNameStr = (row.itineraryBudgetCheckResponseList || []).map(item => item.expenseTypeName).join('、');
              return (
                <div>
                  {row.itineraryHeadDTO.fromCityName}-{row.itineraryHeadDTO.toCityName}：{expenseNameStr}
                </div>
              )
            })}
          </div>
        );
        this.travelErrorList.push({
          type: 'ERROR',
          title: messages('request-1.key131')/*请填写以下行程明细中的必填项*/,
          content: content
        });
      }

      //处理行程明细必填
      let detailRequired = res.data.itineraryBudgetDetailRequiredCheckResponse;
      if (detailRequired && (detailRequired.property === 'ERROR' || detailRequired.property === 'WARN')
        && detailRequired.emptyDetailItineraryHeadList && detailRequired.emptyDetailItineraryHeadList.length) {
        let content = (
          <div>
            {detailRequired.emptyDetailItineraryHeadList.map(row => {
              let rowStartDate = moment(row.startDate).format('YYYY-MM-DD');
              let rowEndDate = moment(row.endDate).format('YYYY-MM-DD');
              return (
                <div>
                  {rowStartDate}~{rowEndDate}&nbsp;&nbsp;&nbsp;{row.fromCityName}-{row.toCityName}
                </div>
              );
            })}
          </div>
        );
        this.travelErrorList.push({
          type: detailRequired.property === 'ERROR' ? 'ERROR' : 'WARNING',
          title: detailRequired.title,
          message: detailRequired.message,
          content: content
        });
      }

      //处理通用报错结果
      if (res.data.checkResults && res.data.checkResults.length) {
        this.travelErrorList.push(...res.data.checkResults);
      }

      if (this.travelErrorList.length) {
        this.setState({submitCheckVisible: true});
      } else {
        this.doRealExecuteTravelSubmitBefore();
      }
    }).catch(err => {
      errorMessage(err.response);
      this.setState({submitLoading: false});
    });
  };

  closeSubmitCheckModal = () => {
    this.setState({submitCheckVisible: false, submitLoading: false});
  };

  //type 'cancel'返回 'submit'继续提交
  handleSubmitCheckModal = (type) => {
    this.setState({submitCheckVisible: false});
    if (type === 'cancel') {
      this.setState({submitLoading: false});
    }
    if (type === 'submit') {
      this.doRealExecuteTravelSubmitBefore();
    }
  };

  doRealExecuteTravelSubmitBefore = () => {
    const { form: formInfo } = this.context;
    let params = {
      formOID: formInfo.formOID,
      applicantOID: this.travelParams.applicantOID,
    };
    requestService.getIsDesignate(params).then(res => {
      let isDesignate = res.data && res.data.showDesignate;
      if (isDesignate) {
        //如果是指派的需要先保存当前单据
        travelService.saveTravelRequest(this.travelParams).then(res => {
          //差旅单不存在新建走到这，肯定是保存状态走到这
          requestService.getNodeList({
            entityOID: res.data.applicationOID,
            entityType: 1001
          }).then(result => {
            let nodeList = result.data.approvalDesignateNodeList || [];
            if (nodeList.length) {
              this.setState({
                designateVisible: true,
                nodeList
              });
            } else {
              this.doRealExecuteTravelSubmit();
            }
          }).catch(err => {
            this.setState({submitLoading: false});
            errorMessage(err.response);
          });
        }).catch(err => {
          this.setState({submitLoading: false});
          errorMessage(err.response);
        });
      } else {
        this.doRealExecuteTravelSubmit();
      }
    }).catch(err => {
      this.setState({submitLoading: false});
      errorMessage(err.response);
    });
  };

  //关闭指派弹框
  //isSuccess 是否是成功的指派选人
  handleCloseDesignate = (isSuccess) => {
    this.setState({designateVisible: false});
    if (isSuccess) {
      this.doRealExecuteTravelSubmit();
    } else {
      this.setState({submitLoading: false});
    }
  };

  //提交差旅申请单
  doRealExecuteTravelSubmit = (isIgnoreBudget, budgetCheckMessage) => {
    const { close } = this.context;
    if (isIgnoreBudget) {
      //是否强制提交
      this.travelParams.ignoreBudgetWarningFlag = true;
      this.travelParams.budgetCheckMessage = budgetCheckMessage;
    }
    travelService.submitTravelRequest(this.travelParams).then(res => {
      this.setState({loading: false, submitLoading: false});
      if (!isIgnoreBudget && res.data && res.data.applicationDTO && res.data.applicationDTO.budgetCheckResult
        && res.data.applicationDTO.budgetCheckResult.checkResultList.length) {
        let checkResultList = res.data.applicationDTO.budgetCheckResult.checkResultList;
        let isForce = checkResultList.filter(item => item.type === 1).length > 0; //是否强制管控 true 强管控， false 弱管控
        let content = (
          <div className="expense-check-result">
            <div className="check-result-item">
              {checkResultList.map(oneResult => {
                return (
                  <div className={`check-result-message ${oneResult.type === 0 ? 'weak-control' : 'strong-control'}`}>
                    {oneResult.message}
                  </div>
                )
              })}
            </div>
          </div>
        );
        if (isForce) {
          //弹框提示超预算
          Modal.error({
            title: messages('request-1.key132')/*检查结果*/,
            content: content,
            okText: messages('request-1.key133')/*返回修改*/,
            onOk: () => this.pureCancelSubmit(res.data.applicationDTO)
          });
        } else {
          //弹框提示是否继续提交
          Modal.confirm({
            title: messages('request-1.key132')/*检查结果*/,
            content: content,
            okText: messages('request-1.key134')/*继续提交*/,
            cancelText: messages('request-1.key133')/*返回修改*/,
            onOk: () => this.doRealExecuteTravelSubmit(true, res.data.applicationDTO.budgetCheckMessage),
            onCancel: () => this.pureCancelSubmit(res.data.applicationDTO)
          });
        }
      } else {
        message.success(messages('request-1.key135')/*提交成功*/);
        close(true);
      }
    }).catch(err => {
      this.setState({submitLoading: false});
      if(this.submitError(err)){
        return;
      }
      errorMessage(err.response);
    });
  };

  //applicationDTO 提交失败要刷新部分数据
  pureCancelSubmit = (applicationDTO) => {
    const { refreshInfo } = this.context;
    this.setState({submitLoading: false});
    if (applicationDTO) {
      refreshInfo();
    }
  };

  submitError = (e) => {
    let data = e.response.data;
    if (data && data.errorCode === '6017007'){
      Modal.warning({
        title: messages('request-1.key136')/*购买的服务已到期，请联系客服*/,
        content: '400 829 7878',
      });
      return true;
    }
  };

  render() {
    const { submitLoading, isShowModal, uniformShow, uniformSwitchShow, uniformValue, selectPerson, platformPerson,
      flightPerson, flightPlatformPerson, trainPerson, diningPerson, hotelPerson, randomHotel, maxHotel, maleUserOIDs,
      femaleUserOIDs, submitCheckVisible, designateVisible, nodeList } = this.state;
    const { info } = this.context;
    return (
      <div className="request-btn">
        <Button className="request-btn" type="primary" onClick={this.handleSubmit} loading={submitLoading}>{messages('common.submit')/*提交*/}</Button>
        <Modal
          title={messages('request-1.key137')/*预订设置*/}
          visible={isShowModal}
          onOk={this.goSubmitTravel}
          onCancel={this.cancelSubmit}
          width={'50%'}
          okText={messages('common.ok')/*确定*/}
          cancelText={messages('common.back')/*返回*/}
        >
          <If value={isShowModal}>
            <If value={uniformShow.flight}>
              <Row type="flex" align="middle" style={{lineHeight: '32px'}}>
                <Col span={6}>
                  <span>{messages('request-1.key138')/*统一订机票*/}：</span>
                </Col>
                <Col span={4}>
                  <If value={uniformSwitchShow.flight}>
                    <Switch
                      checked={uniformValue.isFlight}
                      onChange={() => this.onChangeSwitch('flight')}
                    />
                  </If>
                </Col>
                <Col span={14}>
                  <If value={uniformValue.isFlight}>
                    <Row type="flex" align="middle">
                      <Col span={8}>{messages('request-1.key139')/*预订人*/}</Col>
                      <Col span={14} offset={1}>
                        <Select
                          getPopupContainer={triggerNode => triggerNode.parentNode}
                          onChange={(value) => this.handleChangeUniform(value, 'flight')}
                          value={flightPerson || undefined}
                          placeholder={messages('common.select')/*请选择*/}
                          style={{width: '100%'}}
                        >
                          {selectPerson.map(p => <Option opt={p} key={p.oid}>{p.name}</Option>)}
                        </Select>
                      </Col>
                    </Row>
                  </If>
                  <If value={!uniformValue.isFlight}>
                    {messages('request-1.key140',{arg1: info.createdName})/*参与人各自预订，外部参与人由{arg1}代订*/}
                  </If>
                </Col>
              </Row>
            </If>
            <If value={uniformShow.flightPlatform}>
              <Row type="flex" align="middle" style={{marginTop: 12, lineHeight: '32px'}}>
                <Col span={10}>
                  <span>{messages('request-1.key141')/*统一订机票（订票平台）*/}：</span>
                </Col>
                <Col span={14}>
                  <Row type="flex" align="middle">
                    <Col span={8}>{messages('request-1.key139')/*预订人*/}</Col>
                    <Col span={14} offset={1}>
                      <Select
                        getPopupContainer={triggerNode => triggerNode.parentNode}
                        onChange={(value) => this.handleChangeUniform(value, 'flightPlatform')}
                        value={flightPlatformPerson || undefined}
                        placeholder={messages('common.select')/*请选择*/}
                        style={{width: '100%'}}
                      >
                        {platformPerson.map(p => <Option opt={p} key={p.oid}>{p.name}</Option>)}
                      </Select>
                    </Col>
                  </Row>
                </Col>
              </Row>
            </If>
            <If value={uniformShow.train}>
              <Row type="flex" align="middle" style={{marginTop: 12, lineHeight: '32px'}}>
                <Col span={6}>
                  <span>{messages('request-1.key142')/*统一订火车票*/}：</span>
                </Col>
                <Col span={4}>
                  <If value={uniformSwitchShow.train}>
                    <Switch
                      checked={uniformValue.isTrain}
                      onChange={() => this.onChangeSwitch('train')}
                    />
                  </If>
                </Col>
                <Col span={14}>
                  <If value={uniformValue.isTrain}>
                    <Row type="flex" align="middle">
                      <Col span={8}>{messages('request-1.key139')/*预订人*/}</Col>
                      <Col span={14} offset={1}>
                        <Select
                          getPopupContainer={triggerNode => triggerNode.parentNode}
                          onChange={(value) => this.handleChangeUniform(value, 'train')}
                          value={trainPerson || undefined}
                          placeholder={messages('common.select')/*请选择*/}
                          style={{width: '100%'}}
                        >
                          {selectPerson.map(p => <Option opt={p} key={p.oid}>{p.name}</Option>)}
                        </Select>
                      </Col>
                    </Row>
                  </If>
                  <If value={!uniformValue.isTrain}>
                    {messages('request-1.key140',{arg1: info.createdName})/*参与人各自预订，外部参与人由{arg1}代订*/}
                  </If>
                </Col>
              </Row>
            </If>
            <If value={uniformShow.dining}>
              <Row type="flex" align="middle" style={{marginTop: 12, lineHeight: '32px'}}>
                <Col span={6}>
                  <span>{messages('request-1.key143')/*统一订餐*/}：</span>
                </Col>
                <Col span={4}>
                  <If value={uniformSwitchShow.dining}>
                    <Switch
                      checked={uniformValue.isDining}
                      onChange={() => this.onChangeSwitch('dining')}
                    />
                  </If>
                </Col>
                <Col span={14}>
                  <If value={uniformValue.isDining}>
                    <Row type="flex" align="middle">
                      <Col span={8}>{messages('request-1.key139')/*预订人*/}</Col>
                      <Col span={14} offset={1}>
                        <Select
                          getPopupContainer={triggerNode => triggerNode.parentNode}
                          onChange={(value) => this.handleChangeUniform(value, 'dining')}
                          value={diningPerson || undefined}
                          placeholder={messages('common.select')/*请选择*/}
                          style={{width: '100%'}}
                        >
                          {selectPerson.map(p => <Option opt={p} key={p.oid}>{p.name}</Option>)}
                        </Select>
                      </Col>
                    </Row>
                  </If>
                  <If value={!uniformValue.isDining}>
                    {messages('request-1.key140',{arg1: info.createdName})/*参与人各自预订，外部参与人由{arg1}代订*/}
                  </If>
                </Col>
              </Row>
            </If>
            <If value={uniformShow.hotel}>
              <Row type="flex" align="top" style={{marginTop: 12, lineHeight: '32px'}}>
                <Col span={6}>
                  <span>{messages('request-1.key144')/*统一订酒店*/}：</span>
                </Col>
                <Col span={4}>
                  <If value={uniformSwitchShow.hotel}>
                    <Switch
                      checked={uniformValue.isHotel}
                      onChange={() => this.onChangeSwitch('hotel')}
                    />
                  </If>
                </Col>
                <Col span={14}>
                  <If value={uniformValue.isHotel}>
                    <Row type="flex" align="middle">
                      <Col span={8}>{messages('request-1.key139')/*预订人*/}</Col>
                      <Col span={14} offset={1}>
                        <Select
                          getPopupContainer={triggerNode => triggerNode.parentNode}
                          onChange={(value) => this.handleChangeUniform(value, 'hotel')}
                          value={hotelPerson || undefined}
                          placeholder={messages('common.select')/*请选择*/}
                          style={{width: '100%'}}
                        >
                          {selectPerson.map(p => <Option opt={p} key={p.oid}>{p.name}</Option>)}
                        </Select>
                      </Col>
                    </Row>
                  </If>
                  <If value={!uniformValue.isHotel}>
                    {messages('request-1.key145',{arg1: info.createdName})/*请选择合住房间的预订人，非合住人员各自预订，外部参与人由 {arg1} 代订*/}
                    {/* 酒店非统一订票*/}
                    <If value={maxHotel.maleRoomNumber > 0 || maxHotel.femaleRoomNumber > 0}>
                      <Row type="flex" align="middle">
                        <Col span={8}>{messages('request-1.key146')/*合住房间预订人*/}</Col>
                        <Col span={14} offset={1}>
                          <Button type='primary' loading={randomHotel} ghost onClick={this.createHotelPeople}>{messages('request-1.key147')/*随机*/}</Button>
                        </Col>
                      </Row>
                    </If>
                    <If value={maxHotel.maleRoomNumber > 0}>
                      <Row type="flex" align="middle" style={{marginTop: 12}}>
                        <Col span={8}>{messages('request-1.key148')/*男士*/}</Col>
                        <Col span={14} offset={1}>
                          <Select
                            mode="multiple"
                            optionFilterProp="children"
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            placeholder={messages('common.select')/*请选择*/}
                            value={maleUserOIDs.length ? maleUserOIDs : undefined}
                            onChange={(values) => this.handleSelectItemValue(values, 'maleUserOIDs')}
                            style={{width: '100%'}}
                          >
                            {maxHotel.maleUsers && maxHotel.maleUsers.map(p => <Option opt={p} key={p.userOID}>{p.fullName}</Option>)}
                          </Select>
                        </Col>
                      </Row>
                    </If>
                    <If value={maxHotel.femaleRoomNumber > 0}>
                      <Row type="flex" align="middle" style={{marginTop: 12}}>
                        <Col span={8}>{messages('request-1.key149')/*女士*/}</Col>
                        <Col span={14} offset={1}>
                          <Select
                            mode="multiple"
                            optionFilterProp="children"
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            placeholder={messages('common.select')/*请选择*/}
                            value={femaleUserOIDs.length ? femaleUserOIDs : undefined}
                            onChange={(values) => this.handleSelectItemValue(values, 'femaleUserOIDs')}
                            style={{width: '100%'}}
                          >
                            {maxHotel.femaleUsers && maxHotel.femaleUsers.map(p => <Option opt={p} key={p.userOID}>{p.fullName}</Option>)}
                          </Select>
                        </Col>
                      </Row>
                    </If>
                  </If>
                </Col>
              </Row>
            </If>
          </If>
        </Modal>
        <Modal
          title={messages('common.info')/*提示*/}
          visible={submitCheckVisible}
          onCancel={this.closeSubmitCheckModal}
          maskClosable={false}
          destroyOnClose={true}
          width={540}
          footer={this.travelErrorList.filter(item => item.type === 'ERROR').length ? [
              <Button key="save" onClick={() => this.handleSubmitCheckModal('cancel')}>{messages('common.back')/*返回*/}</Button>
            ] :[
              <Button key="save" onClick={() => this.handleSubmitCheckModal('cancel')}>{messages('common.back')/*返回*/}</Button>,
              <Button key="submit" type="primary" onClick={() => this.handleSubmitCheckModal('submit')}>{messages('request-1.key134')/*继续提交*/}</Button>
            ]}
          wrapClassName="travel-submit-check-modal"
        >
          <div style={{maxHeight: '210px', overflowY: 'auto'}}>
            {this.travelErrorList.map(item => {
              return (
                <div style={{marginBottom: 12}}>
                  <div style={{display: 'inline-block', position: 'relative'}}>
                    <span className="title">{item.title}</span>
                    <div className={`title-base ${item.type === 'ERROR' ? 'title-error' : 'title-warning'}`} />
                  </div>
                  <div>{item.message}</div>
                  {item.content}
                </div>
              )
            })}
          </div>
        </Modal>
        <Designate
          entity={{
            entityType: 1001,
            entityOID: info.applicationOID
          }}
          modalVisible={designateVisible}
          nodeList={nodeList}
          onClose={this.handleCloseDesignate}
        />
      </div>
    )
  }
}

SubmitBtn.contextTypes = {
  applicant: React.PropTypes.object,
  creditScore: React.PropTypes.object,
  jobInfo: React.PropTypes.object,
  form: React.PropTypes.object,
  info: React.PropTypes.object,
  close: React.PropTypes.func,
  refreshInfo: React.PropTypes.func,
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    newProfile: state.login.options,
  }
}

export default connect(mapStateToProps)(SubmitBtn)
